import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;

public class Schedule {
    private Movie movie;
    private Hall hall;
    private String timeSlot;
    private double price;
    private List<Ticket> tickets;
    
    // 静态列表存储所有场次
    private static List<Schedule> schedules = new ArrayList<>();
    private static List<Hall> cinemaHalls = new ArrayList<>();
    private static final String SCHEDULE_FILE = "data/schedules.txt";
    private static final String HALL_FILE = "data/halls.txt";
    
    static {
        loadHalls();
        // 如果没有数据，添加默认放映厅
        if (cinemaHalls.isEmpty()) {
            cinemaHalls.add(new Hall("黄金厅", 8, 10));
            cinemaHalls.add(new Hall("白银厅", 10, 12));
            cinemaHalls.add(new Hall("翡翠厅", 7, 8));
            cinemaHalls.add(new Hall("钻石厅", 7, 8));
            cinemaHalls.add(new Hall("宝石厅", 8, 9));
            saveHalls();
        }
        
        loadSchedules();
        // 如果没有数据，添加一些默认场次
        if (schedules.isEmpty()) {
            List<Movie> movies = Movie.getMovies();
            if (!movies.isEmpty()) {
                schedules.add(new Schedule(movies.get(0), cinemaHalls.get(0), "2024-06-01 19:00", 50));
                schedules.add(new Schedule(movies.get(1), cinemaHalls.get(1), "2024-06-01 20:00", 45));
                schedules.add(new Schedule(movies.get(2), cinemaHalls.get(2), "2024-06-01 18:30", 40));
                saveSchedules();
            }
        }
    }

    public Schedule(Movie movie, Hall hall, String timeSlot, double price) {
        this.movie = movie;
        this.hall = hall;
        this.timeSlot = timeSlot;
        this.price = price;
        this.tickets = new ArrayList<>();
    }

    public Movie getMovie() { return movie; }
    public Hall getHall() { return hall; }
    public String getTimeSlot() { return timeSlot; }
    public double getPrice() { return price; }
    public List<Ticket> getTickets() { return tickets; }

    public void setMovie(Movie movie) { this.movie = movie; }
    public void setHall(Hall hall) { this.hall = hall; }
    public void setTimeSlot(String timeSlot) { this.timeSlot = timeSlot; }
    public void setPrice(double price) { this.price = price; }
    
    // 静态方法：添加场次
    public static void addSchedule(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        Movie selectedMovie = null;
        for (Movie m : Movie.getMovies()) {
            if (m.getName().equals(movieName)) {
                selectedMovie = m;
                break;
            }
        }
        if (selectedMovie == null) {
            System.out.println("未找到该影片。");
            return;
        }
        
        System.out.println("请选择放映厅：");
        for (int i = 0; i < cinemaHalls.size(); i++) {
            System.out.printf("%d. %s\n", i + 1, cinemaHalls.get(i).getName());
        }
        int hallChoice;
        try {
            hallChoice = Integer.parseInt(scanner.nextLine()) - 1;
            if (hallChoice < 0 || hallChoice >= cinemaHalls.size()) {
                System.out.println("选择无效。");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("输入有误。");
            return;
        }
        
        System.out.println("请输入场次时间（格式：2024-06-01 19:00）：");
        String timeSlot = scanner.nextLine();
        
        System.out.println("请输入票价：");
        double price;
        try {
            price = Double.parseDouble(scanner.nextLine());
        } catch (NumberFormatException e) {
            System.out.println("票价输入有误。");
            return;
        }
        
        Schedule schedule = new Schedule(selectedMovie, cinemaHalls.get(hallChoice), timeSlot, price);
        schedules.add(schedule);
        saveSchedules();
        System.out.println("场次添加成功。");
    }
    
    // 静态方法：删除场次
    public static void deleteSchedule(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        System.out.println("请输入场次时间：");
        String timeSlot = scanner.nextLine();
        
        Schedule toDelete = null;
        for (Schedule s : schedules) {
            if (s.getMovie().getName().equals(movieName) && s.getTimeSlot().equals(timeSlot)) {
                toDelete = s;
                break;
            }
        }
        
        if (toDelete == null) {
            System.out.println("未找到该场次。");
            return;
        }
        
        System.out.printf("确定要删除场次 %s - %s 吗？(y/n): ", movieName, timeSlot);
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            schedules.remove(toDelete);
            saveSchedules();
            System.out.println("场次已删除。");
        } else {
            System.out.println("操作已取消。");
        }
    }
    
    // 静态方法：修改场次
    public static void modifySchedule(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        System.out.println("请输入场次时间：");
        String timeSlot = scanner.nextLine();
        
        Schedule toModify = null;
        for (Schedule s : schedules) {
            if (s.getMovie().getName().equals(movieName) && s.getTimeSlot().equals(timeSlot)) {
                toModify = s;
                break;
            }
        }
        
        if (toModify == null) {
            System.out.println("未找到该场次。");
            return;
        }
        
        System.out.printf("当前票价: %.2f, 请输入新票价（回车跳过）：\n", toModify.getPrice());
        String priceStr = scanner.nextLine();
        if (!priceStr.isEmpty()) {
            try {
                double price = Double.parseDouble(priceStr);
                toModify.setPrice(price);
                saveSchedules();
            } catch (NumberFormatException e) {
                System.out.println("票价输入有误，未修改。");
            }
        }
        
        System.out.println("场次信息已修改。");
    }
    
    // 静态方法：列出所有场次
    public static void listAllSchedules() {
        if (schedules.isEmpty()) {
            System.out.println("当前没有场次信息。");
            return;
        }
        System.out.println("\n所有场次信息:");
        for (Schedule s : schedules) {
            System.out.printf("影片: %s, 放映厅: %s, 时间: %s, 票价: %.2f\n",
                s.getMovie().getName(), s.getHall().getName(), s.getTimeSlot(), s.getPrice());
        }
    }
    
    // 静态方法：查询场次座位
    public static void queryScheduleSeats(Scanner scanner) {
        System.out.println("请输入影片名：");
        String movieName = scanner.nextLine();
        System.out.println("请输入场次时间：");
        String timeSlot = scanner.nextLine();
        
        Schedule found = null;
        for (Schedule s : schedules) {
            if (s.getMovie().getName().equals(movieName) && s.getTimeSlot().equals(timeSlot)) {
                found = s;
                break;
            }
        }
        
        if (found == null) {
            System.out.println("未找到该场次。");
            return;
        }
        
        Hall hall = found.getHall();
        Seat[][] seats = hall.getSeats();
        System.out.printf("场次：%s - %s，放映厅：%s\n", movieName, timeSlot, hall.getName());
        System.out.println("座位分布（O=空闲，X=已售）：");
        for (int i = 0; i < hall.getRows(); i++) {
            for (int j = 0; j < hall.getSeatsPerRow(); j++) {
                System.out.print(seats[i][j].isOccupied() ? "X " : "O ");
            }
            System.out.println();
        }
    }
    
    // 静态方法：自动排片
    public static void autoSchedule() {
        // 简单的自动排片逻辑
        System.out.println("自动排片功能待实现。");
    }
    
    // 静态方法：获取所有场次
    public static List<Schedule> getSchedules() { return schedules; }
    
    // 静态方法：获取所有放映厅
    public static List<Hall> getAllHalls() { return cinemaHalls; }
    
    // 文件持久化方法
    private static void saveSchedules() {
        try {
            File dataDir = new File("data");
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }
            
            FileWriter writer = new FileWriter(SCHEDULE_FILE);
            for (Schedule schedule : schedules) {
                writer.write(String.format("%s|%s|%s|%.2f\n",
                    schedule.getMovie().getName(), schedule.getHall().getName(),
                    schedule.getTimeSlot(), schedule.getPrice()));
            }
            writer.close();
        } catch (IOException e) {
            System.out.println("保存场次数据失败: " + e.getMessage());
        }
    }
    
    private static void loadSchedules() {
        try {
            File file = new File(SCHEDULE_FILE);
            if (!file.exists()) {
                return;
            }
            
            Scanner fileScanner = new Scanner(file);
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                String[] parts = line.split("\\|");
                if (parts.length >= 4) {
                    String movieName = parts[0];
                    String hallName = parts[1];
                    String timeSlot = parts[2];
                    double price = Double.parseDouble(parts[3]);
                    
                    // 查找对应的电影和放映厅
                    Movie movie = null;
                    for (Movie m : Movie.getMovies()) {
                        if (m.getName().equals(movieName)) {
                            movie = m;
                            break;
                        }
                    }
                    
                    Hall hall = null;
                    for (Hall h : cinemaHalls) {
                        if (h.getName().equals(hallName)) {
                            hall = h;
                            break;
                        }
                    }
                    
                    if (movie != null && hall != null) {
                        schedules.add(new Schedule(movie, hall, timeSlot, price));
                    }
                }
            }
            fileScanner.close();
        } catch (IOException e) {
            System.out.println("加载场次数据失败: " + e.getMessage());
        }
    }
    
    private static void saveHalls() {
        try {
            File dataDir = new File("data");
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }
            
            FileWriter writer = new FileWriter(HALL_FILE);
            for (Hall hall : cinemaHalls) {
                writer.write(String.format("%s|%d|%d\n",
                    hall.getName(), hall.getRows(), hall.getSeatsPerRow()));
            }
            writer.close();
        } catch (IOException e) {
            System.out.println("保存放映厅数据失败: " + e.getMessage());
        }
    }
    
    private static void loadHalls() {
        try {
            File file = new File(HALL_FILE);
            if (!file.exists()) {
                return;
            }
            
            Scanner fileScanner = new Scanner(file);
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                String[] parts = line.split("\\|");
                if (parts.length >= 3) {
                    String name = parts[0];
                    int rows = Integer.parseInt(parts[1]);
                    int seatsPerRow = Integer.parseInt(parts[2]);
                    cinemaHalls.add(new Hall(name, rows, seatsPerRow));
                }
            }
            fileScanner.close();
        } catch (IOException e) {
            System.out.println("加载放映厅数据失败: " + e.getMessage());
        }
    }
} 